<!-- src/pages/hot/hot.vue -->
<script setup lang="ts">
// 热门推荐页 标题和url
import { getHotDataApi } from '@/api/home'
import { ref } from 'vue'
import type { HotSubType } from '@/types/home'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'

// 页面配置数据：定义不同推荐类型的标题和接口路径
const hotMap = [
  { type: '1', title: '特惠推荐', url: '/hot/preference' },
  { type: '2', title: '爆款推荐', url: '/hot/inVogue' },
  { type: '3', title: '一站买全', url: '/hot/oneStop' },
  { type: '4', title: '新鲜好物', url: '/hot/new' },
]
// 路由参数处理：获取当前页面类型参数
const query = defineProps<{
  type: string
}>()

// 根据路由类型获取对应的配置项
const currentUrlMap = hotMap.find((item) => item.type === query.type)
uni.setNavigationBarTitle({ title: currentUrlMap!.title })

// 封面图
const bannerPicture = ref('')
// 所有分类数据，并且每个分类添加一个 finish 属性，用于判断是否加载完成
// 为什么这里把这个属性设置成可选的呢？因为后端返回的数据本来就没有 finish 属性，所以这里要设置可选
const subTypes = ref<(HotSubType & { finish?: boolean })[]>([])
// 当前选中的分类下标
const activeIndex = ref(0)

// 获取初始数据（包括所有分类数据）
const getHotData = async () => {
  const res = await getHotDataApi(currentUrlMap!.url)
  bannerPicture.value = res.result.bannerPicture
  subTypes.value = res.result.subTypes
}
getHotData()

const isLoading = ref(false) // 🔐 锁变量
// 滚动触底加载更多
const onScrolltolower = async () => {
  if (isLoading.value) return // 1️⃣ 检查锁状态
  isLoading.value = true // 2️⃣ 加锁

  try {
    // 获取当前分类数据，并且 currSubType 其实就是 subTypes 里的一个对象
    // 修改 currSubType 相当于修改了原数据
    const currSubType = subTypes.value[activeIndex.value]
    // 3️⃣ 分页控制：当前页 >= 总页数时停止加载
    if (currSubType.goodsItems.page >= currSubType.goodsItems.pages) {
      currSubType.finish = true
      return uni.showToast({ icon: 'none', title: '没有更多数据~' })
    }
    // 4️⃣ 请求下一页数据
    currSubType.goodsItems.page++
    const res = await getHotDataApi(currentUrlMap!.url, {
      subType: currSubType.id,
      page: currSubType.goodsItems.page,
    })

    // 添加新数据
    const newSubtype = res.result.subTypes[activeIndex.value]
    currSubType.goodsItems.items.push(...newSubtype.goodsItems.items)
  } finally {
    isLoading.value = false // 5️⃣ 释放锁（确保异常时也能解锁）
  }
}

// 转发给朋友
onShareAppMessage(() => ({
  title: '小兔鲜商城',
  path: '/pages/hot/hot' + query.type,
}))
// 转发到朋友圈
onShareTimeline(() => ({
  query: query.type,
}))
</script>

<template>
  <view class="viewport">
    <!-- 推荐封面图 -->
    <view class="cover">
      <image :src="bannerPicture"></image>
    </view>
    <!-- 分类标签栏 -->
    <view class="tabs">
      <text
        v-for="(subType, index) in subTypes"
        :key="subType.id"
        class="text"
        :class="{ active: index === activeIndex }"
        @click="activeIndex = index"
      >
        {{ subType.title }}
      </text>
    </view>
    <!-- 商品列表区域（根据分类切换显示） -->
    <scroll-view
      scroll-y
      class="scroll-view"
      v-for="(subType, index) in subTypes"
      :key="subType.id"
      v-show="index === activeIndex"
      @scrolltolower="onScrolltolower"
    >
      <view class="goods">
        <navigator
          hover-class="none"
          class="navigator"
          v-for="goods in subType.goodsItems.items"
          :key="goods.id"
          :url="`/pages/goods/goods?id=${goods.id}`"
        >
          <!-- #ifdef MP-WEIXIN -->
          <image class="thumb" :src="goods.picture" lazy-load></image>
          <!-- #endif -->
          <!-- #ifdef APP-PLUS || H5 -->
          <img class="thumb" :src="goods.picture" loading="lazy" alt="" />
          <!-- #endif -->
          <view class="name ellipsis">{{ goods.name }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ goods.price }}</text>
          </view>
        </navigator>
      </view>
      <view class="loading-text">{{ subType.finish ? '没有更多数据~' : '正在加载...' }}</view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 180rpx 0 0;
  position: relative;
}

.cover {
  width: 750rpx;
  height: 225rpx;
  border-radius: 0 0 40rpx 40rpx;
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
}

.tabs {
  display: flex;
  justify-content: space-evenly;
  height: 100rpx;
  line-height: 90rpx;
  margin: 0 20rpx;
  font-size: 28rpx;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 5rpx rgba(200, 200, 200, 0.3);
  color: #333;
  background-color: #fff;
  position: relative;
  z-index: 9;

  .text {
    margin: 0 20rpx;
    position: relative;
  }

  .active {
    &::after {
      content: '';

      position: absolute;
      left: 50%;
      bottom: 24rpx;

      width: 40rpx;
      height: 4rpx;

      transform: translate(-50%);
      background-color: #27ba9b;
    }
  }
}

.goods {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20rpx 20rpx;

  .navigator {
    width: 345rpx;
    padding: 20rpx;
    margin-top: 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  .thumb {
    width: 305rpx;
    height: 305rpx;
  }

  .name {
    height: 88rpx;
    font-size: 26rpx;
  }

  .price {
    color: #cf4444;
    font-size: 30rpx;
  }

  .symbol {
    font-size: 70%;
  }
}

.loading-text {
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 20rpx 0 50rpx;
}
</style>
